package com.hotacorp.opencloud.gateway.exception;

import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;

import com.alibaba.fastjson.JSONObject;
import com.hotacorp.opencloud.common.commdata.Result;

import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * 当服务不可用时的异常处理
 * @author lwg
 *
 */
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class GlobalExceptionHandler implements ErrorWebExceptionHandler {

    @Override
    public Mono<Void> handle(ServerWebExchange serverWebExchange, Throwable throwable) {

        //log.info("GLOBAL EXCEPTION:{}, \n{}", serverWebExchange.getRequest().getPath(), throwable);
        Result<String> result = new Result<String>("", 500, "");
        if (throwable instanceof ResponseStatusException) {
        	result.setCode(((ResponseStatusException)throwable).getStatus().value());
        	result.setMsg(((ResponseStatusException)throwable).getLocalizedMessage());
        } else {
        	result.setCode(500);
        	result.setMsg("系统溜号了");
        }
        String string = JSONObject.toJSONString(result);

        DataBufferFactory bufferFactory = serverWebExchange.getResponse().bufferFactory();
        serverWebExchange.getResponse().getHeaders().setContentType(MediaType.APPLICATION_JSON_UTF8);
        serverWebExchange.getResponse().setStatusCode(HttpStatus.OK);
        return serverWebExchange.getResponse().writeWith(Flux.just(bufferFactory.wrap(string.getBytes())));
    }
}
